iT邦幫忙

2025 iThome 鐵人賽

DAY 24
0
自我挑戰組

leetcode系列 第 24

leetcode 24. Swap Nodes in Pairs

  • 分享至 

  • xImage
  •  

題目:
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.
給定一個鍊錶,交換每兩個相鄰節點並返回其頭節點。你必須在不修改鍊錶節點值的情況下(即只能修改節點本身)解決問題。

給定一個鍊錶,交換每兩個相鄰節點並返回其頭節點。你必須在不修改鍊錶節點值的情況下(即只能修改節點本身)解決問題。

https://ithelp.ithome.com.tw/upload/images/20251008/20169340Fd8aAmlygQ.png
https://ithelp.ithome.com.tw/upload/images/20251008/20169340AygVoBUV3O.png

解題思路(迭代法)

建立 dummy 節點

方便處理交換頭節點的情況。

用指標 prev 指向 dummy 節點,head 指向鏈表開頭。

每次處理兩個節點

記錄 first = head、second = head.next

交換連結:
prev.next = second
first.next = second.next
second.next = first
更新指標:
prev = first
head = first.next


上一篇
leetcode 23. Merge k Sorted Lists
系列文
leetcode24
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言